package com.example.activiti7.controller;

import com.example.activiti7.domain.model.req.ActBizModelReq;
import com.example.activiti7.domain.model.resp.Response;
import com.example.activiti7.domain.service.ProcessDefinitionService;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

@Controller
@RequestMapping("/overflow/resource")
@Tag(name = "流程模型服务能力", description = "流程模型接口服务管理")
public class ResourceController {
    @Resource
    private ProcessDefinitionService processDefinitionService;

    @RequestMapping(value = "/model/create", method = RequestMethod.POST)
    @Operation(summary = "创建流程模型(流程设计器专用)")
    @ResponseBody
    public Response<Model> createModel(@RequestBody ActBizModelReq actModelReq) throws Exception {
//        ActBizModelVO actModel = new ActBizModelVO();
//        actModel.setDescription("流程新建描述");
//        actModel.setName("流程新建");
//        response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
        return processDefinitionService.create(actModelReq);
    }

    @Operation(summary = "获取BPMN流程编辑器JSON模板")
    @GetMapping(value = {"/editor/stencilset"}, produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String getStencilset() throws IOException {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("static/stencilset.json");
        return IOUtils.toString(inputStream, "utf-8");
    }

    @RequestMapping(value = {"/model/{modelId}/save"}, method = {RequestMethod.PUT})
    @Operation(summary = "更新流程模型(流程设计器专用)")
    @ResponseBody
    public boolean saveModel(@PathVariable String modelId, @RequestParam MultiValueMap<String, String> values) throws Exception {
        return processDefinitionService.save(modelId, values);
    }

    @RequestMapping(value = {"/model/{modelId}/json"}, method = RequestMethod.GET, produces = {"application/json"})
    @Operation(summary = "获取流程模型数据(流程设计器专用)")
    @ResponseBody
    public ObjectNode getEditorJson(@PathVariable String modelId) throws Exception {
        return processDefinitionService.getModelEditorJson(modelId);
    }
}
